package table

import (
	"encoding/json"
	"lol.com/feb214-game/nest.git/log"
	"lol.com/feb214-game/nest.git/tools"
	"strconv"
	"talent.com/cube/common/cxt"
	"talent.com/cube/conf/g"
)

//将数据同步到db，完成后移除redis中的期数记录
func SyncCredit2DB(ch chan *cxt.SyncData) {
	tools.RecoverFromPanic(func() {
		log.Error("panic when sync credit to db!!!")
	})
	var (
		after int64
		err   error
	)

	for d := range ch {
		dao := g.GetAccountDAO(d.GameType)
		if d.LogOut {
			extend := make(map[string]interface{})
			extend["game_id"] = strconv.FormatInt(d.TermNumber, 10)
			extend["bet"] = d.Bet
			extend["award"] = 0
			extend["type"] = 1
			extend["withdrawal_rate"] = d.WithdrawalRate
			gameStr, _ := json.Marshal(extend)
			_, after, err = dao.IncrUserCredit(d.UserId, d.Bet, string(gameStr), d.WithdrawalRate)
		} else {
			extend := make(map[string]interface{})
			extend["game_id"] = strconv.FormatInt(d.TermNumber, 10)
			_, after, err = dao.IncrCredit(d.UserId, d.Award, d.Bet, d.TermBet, extend, d.WithdrawalRate) // 落库
			if err != nil {
				//数据库连接异常，未能成功建立下注记录，直接崩溃程序
				log.Fatal("!!!!!!fail to sync %+v for server error:%v", d, err.Error())
				continue
			}
		}
		//因为下注是跟盈利一起同步的，所以不需要下注缓存，只要不结算，那么是不会同步到数据库的。
		g.ServerCloseWG.Done()
		if d.Award != 0 {
			//通知桌子协程更新用户余额
			tc := cxt.GetTableContext(d.TableID)
			if tc != nil {
				d.Award = after
				tc.RPC.Go(g.EventUpdateAfterSettle, d)
			}
		}
	}
}
